#include <fstream>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream> //std::stringstream

using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::string;
using std::vector;
using std::cerr;

using namespace std;

void test1()
{
	ifstream ifs("clear.aac");
    ofstream outFile("example.txt");

    std::ofstream outFile_add;
    outFile_add.open("add.txt", std::ios::app);

	if(!ifs.is_open())
	{
		cerr << "ifstream open file error!\n";
		return;
	}

	ifs.seekg(0, ios_base::end);  //先把文件输入流指针定位到文档末尾来获取文档的长度
	int length = ifs.tellg();
	ifs.seekg(ios_base::beg);  //再将指针定位到文档开头来进行读取
	char* buff = new char[length + 1](); //开辟一个buff
	ifs.read(buff, length + 1);  //将内容读取到buff中

    cout << "len:" << length << endl;
    for (int i = 0; i < length; i++) {
        //printf("0x%02x ", (unsigned char)buff[i]);
        outFile << (unsigned char)buff[i];
        outFile_add << (unsigned char)buff[i];
    }

    for (int i = 0; i < length; i++) {
        //printf("0x%02x ", (unsigned char)buff[i]);
        outFile << (unsigned char)buff[i];
        outFile_add << (unsigned char)buff[i];
    }

    outFile.close();
    outFile_add.close();

    //cout << "read:" << buff << endl;

	/*string content(buff, length + 1); //再将buff赋值给content
	cout << "string:" << content << endl;*/

    ifs.close();
	delete [] buff;
}

int test2(void)
{
	ifstream ifs("test1");
	stringstream buffer;

	buffer << ifs.rdbuf();
	string str(buffer.str());
	cout << str << endl;

    char *p = (char *)str.data();
    cout << "pointer:" << p << endl;

    char *w = (char *)str.c_str();
    cout << "pointer:" << w << endl;

	ifs.close();

	return 0;
}

int main()
{
    ifstream in("test1");  
    char buffer[32] = {0};
    int len = 0;
    
    #if 0
    if (!in.is_open()) {
        cerr << "Fail to open file!" << endl;
        exit(1);
    } 
    else {
        #if 0
        long pos = in.tellg();     // 获取文件指针的位置
        in.seekg(0, ios::beg);     // 设置文件指针的位置到文件开头

        if (pos < 32) {            
            in.read(buffer, (int)(pos-1));  // 从文件中读取 pos 个字节

            printf("< len %d:%s\n", len, buffer);
        }
        else {
            in.read(buffer, 31);  // 从文件中读取 pos 个字节
            printf("> %s\n", buffer);
        }
        #endif

        while (!in.eof())  
        {  
            in.getline (buffer,300);  
            printf("... %s\n", buffer);
            break;
        } 
    }

    in.close();
    #endif 

    test1();
    //test2();

    return 0;
}
